#!/usr/bin/env python3
"""
音频数据发送进程示例
通过管道向WebSocket服务器发送音频数据
"""

import socket
import time
import struct
import platform
import os
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class AudioSender:
    def __init__(self, host='localhost', pipe_port=8766, pipe_path="/tmp/audio_pipe"):
        self.host = host
        self.pipe_port = pipe_port
        self.pipe_path = pipe_path
        self.is_windows = platform.system() == "Windows"
        self.socket = None
        self.pipe_file = None
        
    def connect(self):
        """连接到WebSocket服务器的管道"""
        try:
            if self.is_windows:
                # Windows: 连接到TCP socket
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.socket.connect((self.host, self.pipe_port))
                logger.info(f"已连接到Windows管道端口: {self.pipe_port}")
            else:
                # Unix/Linux: 连接到命名管道
                if not os.path.exists(self.pipe_path):
                    logger.error(f"命名管道不存在: {self.pipe_path}")
                    return False
                
                self.pipe_file = open(self.pipe_path, 'wb')
                logger.info(f"已连接到Unix命名管道: {self.pipe_path}")
            
            return True
            
        except Exception as e:
            logger.error(f"连接管道失败: {e}")
            return False
    
    def send_audio_data(self, audio_data):
        """发送音频数据"""
        try:
            if self.is_windows and self.socket:
                # Windows: 通过TCP socket发送
                self.socket.send(audio_data)
                return True
            elif not self.is_windows and self.pipe_file:
                # Unix: 通过命名管道发送
                self.pipe_file.write(audio_data)
                self.pipe_file.flush()
                return True
            else:
                logger.error("管道未连接")
                return False
                
        except Exception as e:
            logger.error(f"发送音频数据失败: {e}")
            return False
    
    def send_synthetic_audio(self, duration=10, sample_rate=48000, channels=2):
        """发送合成音频数据（用于测试）"""
        logger.info(f"开始发送合成音频数据，时长: {duration}秒")
        
        # 生成测试音频数据（正弦波）
        import math
        
        start_time = time.time()
        sample_count = 0
        
        while time.time() - start_time < duration:
            # 生成一个音频块（4KB）
            chunk_size = 4096
            audio_chunk = bytearray()
            
            for i in range(0, chunk_size, 4):  # 每个样本4字节（2通道，16位）
                if sample_count + i//4 >= sample_rate * duration:
                    break
                    
                # 生成简单的正弦波
                t = (sample_count + i//4) / sample_rate
                frequency = 440  # 440 Hz
                amplitude = 0.3
                
                # 左声道
                left_sample = int(amplitude * 32767 * math.sin(2 * math.pi * frequency * t))
                # 右声道
                right_sample = int(amplitude * 32767 * math.sin(2 * math.pi * frequency * t + math.pi/4))
                
                # 16位PCM，小端序
                audio_chunk.extend(struct.pack('<hh', left_sample, right_sample))
            
            if audio_chunk:
                # 发送音频块
                if self.send_audio_data(bytes(audio_chunk)):
                    logger.debug(f"发送音频块: {len(audio_chunk)} 字节")
                else:
                    logger.error("发送音频块失败")
                    break
            
            sample_count += len(audio_chunk) // 4
            time.sleep(0.033)  # 约30fps
        
        logger.info("合成音频数据发送完成")
    
    def close(self):
        """关闭连接"""
        try:
            if self.is_windows and self.socket:
                self.socket.close()
                self.socket = None
                logger.info("Windows管道连接已关闭")
            elif not self.is_windows and self.pipe_file:
                self.pipe_file.close()
                self.pipe_file = None
                logger.info("Unix管道连接已关闭")
        except Exception as e:
            logger.error(f"关闭管道连接时出错: {e}")

def main():
    """主函数"""
    print("音频数据发送进程")
    print("=" * 50)
    
    # 创建音频发送器
    sender = AudioSender()
    
    try:
        # 连接到管道
        if not sender.connect():
            print("无法连接到管道，请确保WebSocket服务器正在运行")
            return
        
        print("已连接到管道，开始发送音频数据...")
        print("按 Ctrl+C 停止发送")
        
        # 发送合成音频数据
        sender.send_synthetic_audio(duration=30)  # 发送30秒的音频
        
    except KeyboardInterrupt:
        print("\n用户中断，正在停止...")
    except Exception as e:
        print(f"发送音频数据时出错: {e}")
    finally:
        sender.close()
        print("音频数据发送进程已退出")

if __name__ == "__main__":
    main()
